package com.seer.leshantools.server;

import com.google.gson.Gson;
import org.eclipse.leshan.core.node.LwM2mSingleResource;
import org.eclipse.leshan.core.observation.Observation;
import org.eclipse.leshan.core.response.ObserveResponse;
import org.eclipse.leshan.server.observation.ObservationListener;
import org.eclipse.leshan.server.registration.Registration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReturnAdapter implements ObservationListener  {

    private MessageServer messageServer;
    private Gson gson;
    private Logger log = LoggerFactory.getLogger(ReturnAdapter.class);

    public ReturnAdapter(MessageServer messageServer, Gson gson) {
        this.messageServer = messageServer;
        this.gson = gson;
    }

    @Override
    public void newObservation(Observation observation, Registration registration) {
        if (observation.getPath().getResourceId() == ((MessageServerImpl) messageServer).resultId) {
            log.debug("Start to observe return message resource of client {}", registration.getEndpoint());
        }
    }

    @Override
    public void cancelled(Observation observation) {
    }

    @Override
    public void onResponse(Observation observation, Registration registration, ObserveResponse response) {
        // 处理 result 通道的结果
        if (observation.getPath().getResourceId() == ((MessageServerImpl) messageServer).resultId) {
            if (response.isSuccess()) {
                log.debug("Receive return message from client {}", registration.getEndpoint());
                LwM2mSingleResource resource = (LwM2mSingleResource) response.getContent();
                String json = (String) resource.getValue();
                Message m = gson.fromJson(json, Message.class);
                try {
                    messageServer.response(m);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            log.error("Error when receive message from client {}, errCode = {}, errMsg = {}",
                    registration.getEndpoint(),
                    response.getCode(),
                    response.getContent());
        }
    }

    @Override
    public void onError(Observation observation, Registration registration, Exception error) {
        if (observation.getPath().getResourceId() == ((MessageServerImpl) messageServer).resultId) {
            log.error("Cannot  observe return message resource of client {}, err={}",
                    registration.getEndpoint(),
                    error.toString());
        }
    }
}
